package com.chb.javabasic.jdbc.DAO;

import com.chb.javabasic.jdbc.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserDao {
    private final JdbcTemplate jdbcTemplate;

    public UserDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // 使用ResultSet设置User
    private static final RowMapper<User> userRowMapper = new RowMapper<User>() {
        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setEmail(rs.getString("email"));
            user.setCreatedAt(rs.getTimestamp("created_at"));
            user.setUpdatedAt(rs.getTimestamp("updated_at"));
            return user;
        }
    };

    //更新用户
    public int UpdateUser(User user) {
        String sql = "update user set username = ?, password = ?, email = ?, updated_at = ? where id = ?";
        return jdbcTemplate.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getEmail(),
                user.getUpdatedAt(),
                user.getId());
    }

    //根据id删除用户
    public int DeleteById(Long id){
        String sql = "delete from user where id = ?";
        return jdbcTemplate.update(sql, id);
    }

    //插入
    public int insertUser(User user){
        String sql = "INSERT INTO user (username, password, email, created_at, updated_at)"
                +  "VALUES (?,?,?,?,?)";
        return jdbcTemplate.update(sql,
                user.getUsername(),
                user.getPassword(),
                user.getEmail(),
                user.getCreatedAt(),
                user.getUpdatedAt());
    }

    // 根据用户名查询用户
    public List<User> findByUsername(String username) {
        String sql = "SELECT * FROM user WHERE username = ?";
        return jdbcTemplate.query(sql, userRowMapper, username);
    }

}
